package com.vnp.vchat.version2;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;

import com.turbomanage.httpclient.HttpResponse;
import com.vnp.vchat.ChatActivity;
import com.vnp.vchat.KhachhangActivity;
import com.vnp.vchat.MainActivity;
import com.vnp.vchat.MainPanelActivity;
import com.vnp.vchat.R;
import com.vnp.vchat.Util.KeyboardHelper;
import com.vnp.vchat.Util.PreferenceHelper;
import com.vnp.vchat.Util.Utils;
import com.vnp.vchat.adapter.SearchAdapter;
import com.vnp.vchat.bean.ObjKhachhang;
import com.vnp.vchat.httpclient.HttpBasicClientHelper;
import com.vnp.vchat.httpclient.HttpClientHelper;
import com.vnp.vchat.httpclient.MyJsonAsyncCallback;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;

public class TimkiemActivity extends Activity implements OnClickListener{
	
	EditText edtSearch;
	Button btnHuy;
	ListView listResult;
	
	ImageView btnClear;
	PreferenceHelper preferenceHelper;
	String keyword;
	
	LinearLayout vNen;
	TextView txtNoRs;
	
	SearchAdapter adapter;
	ArrayList<ObjKhachhang> objKhachhangs = new ArrayList<ObjKhachhang>();
	ProgressBar progressBar;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_timkiem);
		
		preferenceHelper = new PreferenceHelper(this);
		
		edtSearch = (EditText) findViewById(R.id.edt_search);
		btnHuy = (Button) findViewById(R.id.btn_huy);
		
		vNen = (LinearLayout) findViewById(R.id.v_nen);
		
		listResult = (ListView) findViewById(R.id.list_rs);
		btnClear = (ImageView) findViewById(R.id.btn_clears);
		txtNoRs = (TextView) findViewById(R.id.txt_no_rs);
		progressBar = (ProgressBar) findViewById(R.id.progressBar1);
		objKhachhangs.clear();
		adapter = new SearchAdapter(TimkiemActivity.this, objKhachhangs);
		listResult.setAdapter(adapter);
		
		init();
		setFont();
		
		search();
		
	}
	
	void init(){
		btnHuy.setOnClickListener(this);
		btnClear.setOnClickListener(this);
		vNen.setOnClickListener(this);
		edtSearch.setOnClickListener(this);
	}
	
	void setFont(){
		edtSearch.setTypeface(Utils.getTypefaceRegular(TimkiemActivity.this));
		btnHuy.setTypeface(Utils.getTypefaceRegular(TimkiemActivity.this));
	}
	
	void search(){
		edtSearch.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.toString().length() > 0){
					btnClear.setVisibility(View.VISIBLE);
				} else {
					btnClear.setVisibility(View.GONE);
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				keyword = s.toString();
			}
		});
		
		
		edtSearch.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
					searchUser();
					return true;
			}
		});
	}
	
	void searchUser(){
		objKhachhangs.clear();
		txtNoRs.setVisibility(View.GONE);
		vNen.setVisibility(View.GONE);
		progressBar.setVisibility(View.VISIBLE);
		KeyboardHelper.hideSoftKeyboard(TimkiemActivity.this);
//		Toast.makeText(TimkiemActivity.this, edtSearch.getText().toString(), Toast.LENGTH_SHORT).show();
		HttpBasicClientHelper httpBasicClientHelper = new HttpBasicClientHelper(new MyJsonAsyncCallback(){

			@Override
			public void onSuccess(HttpResponse httpResponse, JSONObject re) {
				int statusCode = httpResponse.getStatus();
				if (statusCode == 200){
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							progressBar.setVisibility(View.GONE);
						}
					});
					
//					Toast.makeText(TimkiemActivity.this, "Re: "+re.toString(), Toast.LENGTH_SHORT).show();
					try {
						Log.i("DATA", "RESULT: "+re.getJSONArray("data"));
						JSONArray ja = re.getJSONArray("data");
						
						if (ja.length() == 0){
							runOnUiThread(new Runnable() {
								
								@Override
								public void run() {
									txtNoRs.setVisibility(View.VISIBLE);
								}
							});
							
						}else {
							for (int i = 0; i < ja.length(); i++) {
								JSONObject user = ja.getJSONObject(i);
								ObjKhachhang objKhachhang = new ObjKhachhang();
								
								String avatar = user.getString("to_image");
								String hash = user.getString("hash");
								String id = user.getString("uss_sso_id");
								String useName = user.getString("use_name");
								String useLoginName = user.getString("use_loginname");
								
								objKhachhang.setUrlAvatar(avatar);
								objKhachhang.setId(id);
								objKhachhang.setName(useName);
								objKhachhang.setLoginName(useLoginName);
								objKhachhang.setUrlDangxem("");
								
								objKhachhangs.add(objKhachhang);
							}
							
							runOnUiThread(new Runnable() {
								
								@Override
								public void run() {
									adapter.notifyDataSetChanged();
									setListView();
								}
							});
						}
						

						
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							progressBar.setVisibility(View.GONE);
							txtNoRs.setVisibility(View.VISIBLE);
							Toast.makeText(TimkiemActivity.this, "Không tìm được kết quả.", Toast.LENGTH_SHORT).show();
						}
					});
				}
			}

			@Override
			public void onFailure(Exception e) {
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						progressBar.setVisibility(View.GONE);
						Toast.makeText(TimkiemActivity.this, "Không tìm được kết quả.", Toast.LENGTH_SHORT).show();
					}
				});
			}
		});
		
		httpBasicClientHelper.searchUser(Integer.parseInt(preferenceHelper.getAdminId()), preferenceHelper.getHashSetting(), edtSearch.getText().toString());
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_huy:
			closeActivity();
			break;
		case R.id.btn_clears:
			edtSearch.setText("");
			break;
		case R.id.edt_search:
			vNen.setVisibility(View.VISIBLE);
			edtSearch.requestFocus();
			break;
		case R.id.v_nen:
			vNen.setVisibility(View.GONE);
			KeyboardHelper.hideSoftKeyboard(TimkiemActivity.this);
			break;
		default:
			break;
		}
	}
	
	@Override
	public void onBackPressed() {
		closeActivity();
	}
	
	void closeActivity(){
		finish();
		overridePendingTransition(R.anim.over_main_right, R.anim.trans_right_out);
	}
	
	
	void setListView(){
		
		Log.i("DATA", "Show ket qua");
		vNen.setVisibility(View.GONE);
		KeyboardHelper.hideSoftKeyboard(TimkiemActivity.this);
				
		listResult.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				MainPanelActivity.onGoto = true;
				Intent c = new Intent(TimkiemActivity.this,ChatNewActivity.class);
				c.putExtra("khachhang", objKhachhangs.get(position));
				startActivity(c);
			}
		});
		
	}
}
